//
//  RBAllViewController.m
//  Budejie
//
//  Created by 华杨科技 on 2017/10/15.
//  Copyright © 2017年 饶波. All rights reserved.
//
 
#import "RBAllViewController.h"
#import <AFNetworking.h>
#import <UIImageView+WebCache.h>
#import <MJExtension.h>
#import "RBTopics.h"
#import "RBRefreshHeader.h"
#import "RBRefreshFooter.h"
#import "RBTopicCell.h"  // 11-27 



@interface RBAllViewController ()
/**新帖数据 */
@property (nonatomic, strong) NSMutableArray *dataArray;
/**maxtime加载下一页数据*/
@property (nonatomic, copy) NSString *maxtime;
/**AFHTTPmanager*/
@property (nonatomic, weak) AFHTTPSessionManager *afnManager;

@end

@implementation RBAllViewController
- (NSArray *)dataArray{
    if (!_dataArray) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}
- (AFHTTPSessionManager *)afnManager {
    if (!_afnManager) {
        _afnManager = [AFHTTPSessionManager manager];
    }
    return _afnManager;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    RBNSLogFunction;
    // 设置内边距,解决tableView被遮盖问题
    self.tableView.contentInset = UIEdgeInsetsMake(64+35, 0, 49, 0);
    // 设置滚动条内边距
    self.tableView.scrollIndicatorInsets = self.tableView.contentInset;
    
    // 11-27 注册cell
    [self.tableView registerNib:[UINib nibWithNibName:@"RBTopicCell" bundle:nil] forCellReuseIdentifier:@"RBTopicCell"];
    
    [self setupReresh];
}
- (void)setupReresh
{
    // 下拉刷新
    RBRefreshHeader *mj_header = [RBRefreshHeader headerWithRefreshingTarget:self refreshingAction:@selector(reloadNewTopics)];
    self.tableView.mj_header = mj_header;
    [self.tableView.mj_header beginRefreshing];
    
    // 上拉加载更多
    RBRefreshFooter *mj_footer = [RBRefreshFooter footerWithRefreshingTarget:self refreshingAction:@selector(reloadMoreTopics)];
    self.tableView.mj_footer = mj_footer;
}

#pragma mark - 请求数据
- (void)reloadNewTopics
{
      
    // 取消请求:下拉刷新和上拉刷新，只能同时存在一个
//    for (NSURLSessionTask *task in self.afnManager.tasks) {
//        [task cancel];
//    }
    [self.afnManager.tasks makeObjectsPerformSelector:@selector(cancel)];    
    
    NSMutableDictionary *parameter = [NSMutableDictionary dictionary];
    [parameter setObject:@"newlist" forKey:@"a"];
    [parameter setObject:@"data" forKey:@"c"];
    [parameter setObject:@"type" forKey:@"31"];
    
    [self.afnManager GET:@"http://api.budejie.com/api/api_open.php" parameters:parameter progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  responseObject) {
//        [responseObject writeToFile:@"/Users/huayangkeji/Desktop/newtopic.plist" atomically:YES];
        
        NSArray *listArr = responseObject[@"list"];
   
        //        [self rb_JSONStringFromDic:responseObject];
        
        self.maxtime = responseObject[@"info"][@"maxtime"];
        self.dataArray = [RBTopics mj_objectArrayWithKeyValuesArray:responseObject[@"list"]];
        [self.tableView reloadData];
        [self.tableView.mj_header endRefreshing];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (error.code == NSURLErrorCancelled) {
            NSLog(@"请求被取消");
        }else{
            NSLog(@"其他错误:%@",error);
//            NSURLErrorCancelled;
        }
        
        [self.tableView.mj_header endRefreshing];
    }];
    
    /**
     服务器数据库的数据 = @[23， 22， 21， 20,19,18,17,15,14,13，12，11，10]
     
     第1页数据 == @[20,19,18,17,16]
     第2页数据 == @[15,14,13,12,11]
     
     做法1:
     发送page参数:page=2
     
     做法2: 最严谨 告诉服务器上一页在哪里。 ✅
     发送maxi参数:maxid=16
     */
}

/**下拉加载更多数据**/
- (void)reloadMoreTopics
{ 
    [self.afnManager.tasks makeObjectsPerformSelector:@selector(cancel)];
    
    NSMutableDictionary *parameter = [NSMutableDictionary dictionary];
    [parameter setObject:@"newlist" forKey:@"a"];
    [parameter setObject:@"data" forKey:@"c"];
    [parameter setObject:@"type" forKey:@"31"];
    [parameter setObject:self.maxtime forKey:@"maxtime"];
    
    [self.afnManager GET:@"http://api.budejie.com/api/api_open.php" parameters:parameter progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  responseObject) {
        
//        RBWriteToPlist(responseObject,@"moreTopic");
        self.maxtime = responseObject[@"info"][@"maxtime"];
        NSArray *moretopics = [RBTopics mj_objectArrayWithKeyValuesArray:responseObject[@"list"]];
        [self.dataArray addObjectsFromArray:moretopics];
        
        // addObejct: 和addObjectsFromArray:
//        [self.dataArray addObject:moretopics];
        // [20,19,18]
        // [17,16,15]
        // [20,19,18,[17,16,15]]  addObject:
        // [20,19,18,17,16,15]    addObjectsFromArray:
        
        [self.tableView reloadData];
        [self.tableView.mj_footer endRefreshing];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"请求失败--%@",error);
        [self.tableView.mj_footer endRefreshing];
    }];    
}


#pragma mark - Table view data source
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    RBTopicCell *cell = [tableView dequeueReusableCellWithIdentifier:@"RBTopicCell"];
    cell.topics = self.dataArray[indexPath.row]; 
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath 
{
    return 218;
}

// 一个任务被取消(cancel)了,会自动进入AFN的failure的block


#pragma mark - Dic 转 JSON
/***将服务器返回的数据 转为JSON串**/
- (NSString *)rb_JSONStringFromDic:(NSDictionary *)dic
{
    NSError *parseError = nil;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&parseError];
        
    NSString *jsonStr = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];

    NSLog(@"jsonStr:%@",jsonStr);
    return jsonStr;
}


@end
